﻿using System;
using System.IO;
using System.Text;

namespace FileTransformer
{
    public class UnexpectedDataEndException : Exception { }

    public static class MemoryStreamHelper
    {
        private static void SafeRead(Stream stream, ref byte[] bytes, int length)
        {
            var readCount = stream.Read(bytes, 0, length);
            if (readCount != length)
                throw new UnexpectedDataEndException();
        }

        public static string HReadName(this MemoryStream stream)
        {
            var length = stream.ReadByte();
            var bytes = new byte[length];
            SafeRead(stream, ref bytes, length);
            return Encoding.Default.GetString(bytes);
        }

        public static int HReadInt(this MemoryStream stream)
        {
            const int int32Size = sizeof(Int32);
            var bytes = new byte[int32Size];
            SafeRead(stream, ref bytes, int32Size);
            return BitConverter.ToInt32(bytes, 0);
        }

        public static void HWrite(this MemoryStream stream, byte[] bytes)
        {
            stream.Write(bytes, 0, bytes.Length);
        }

        public static void HWrite(this MemoryStream stream, string name)
        {
            if (name.Length > 255)
                throw new NameToLongException();

            stream.WriteByte((byte)name.Length);
            HWrite(stream, Encoding.Default.GetBytes(name));
        }

        public static void HWrite(this MemoryStream stream, int value)
        {
            HWrite(stream, BitConverter.GetBytes(value));
        }

        public static void HSave(this MemoryStream stream, string fileName)
        {
            DataUtils.SaveBytesToFile(fileName, stream.ToArray());
        }
    }
}
